package com.kyrie.exception;

import com.kyrie.system.mybatis.execption.ServiceException;
import com.kyrie.utils.GlobalConstants;
import com.kyrie.vo.ResponseBean;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/***
 * 自定义全局controller异常拦截器
 * @author wuxiang
 */
@RestControllerAdvice
public class GlobalExceptionHandlerController {
    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandlerController.class);

    /***
     * 拦截参数校验失败异常
     * @param e MethodArgumentNotValidException
     * @return ResponseBean
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseBean<String> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        logger.info("【参数校验失败: {}】",bindingResult.getFieldError().getDefaultMessage());
        return ResponseBean.notValid("", GlobalConstants.FAIL_CODE, bindingResult.getFieldError().getDefaultMessage());
    }


    /***
     * 数据库操作异常
     * @param e ServiceException
     * @return ResponseBean
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseBean<String> ServiceException(ServiceException e) {
        logger.error("【数据库操作异常】-- catch ServiceException: ",e);
        return ResponseBean.exception("", GlobalConstants.FAIL_CODE, e.getMessage());
    }

    /***
     * token认证失败异常
     * @param e AuthenticationException
     * @return ResponseBean
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public ResponseBean<String> AuthenticationException(AuthenticationException e) {
        logger.error("【token认证失败】-- catch AuthenticationException: ",e);
        return ResponseBean.exception("", GlobalConstants.FAIL_CODE, e.getMessage());
    }

}
